//state对象 保存数据
const state = {
    notes: [],
    timestamps: []
};

//mutations 用于更改state里面的数据
const mutations = {
    ADD_NOTE(state, payload) {
        let newNote = payload;
        state.notes.push(newNote);
    },
    ADD_TIMESTAMP(state, payload) {
        let newTimeStamp = payload;
        state.timestamps.push(newTimeStamp);
    }
};

//actions是调用mutations的函数
//第一个参数是context 
//  context可以访问state: context.state
//  context可以访问getters: context.getters
//  context可以提交数据: context.commit
const actions = {
    addNote(context, payload) {
        context.commit("ADD_NOTE", payload)

    },
    addTimestamp(context, payload) {
        context.commit("ADD_TIMESTAMP", payload)
    }
}

//getters应用程序计算stores里面数据的结果
//参数是state
const getters = {
    /*
    getNotes(state) {
        return state.notes;
    },
    getTimestamps(state) {
        return state.timestamps;
    },
    getNoteCount(state) {
        return state.notes.length;
    }*/
    //和上面的同样的效果 采用箭头函数
    getNotes: state => state.notes,
    getTimestamps: state => state.timestamps,
    getNoteCount: state => state.notes.length,
}

//集成state, mutations, actions, getters 
//形成store
/*
const store = new Vuex.Store({
    state: state,
    mutations: mutations,
    actions: actions,
    getters: getters
});*/
//和上面的同样的效果 采用简写
const store = new Vuex.Store({
    state,
    mutations,
    actions,
    getters
});

const inputComponent = {
    template: `<input 
        placeholder="Enter a note"
        v-model="input"
        @keyup.enter="monitorEntryKey"
        class='input is-small' type='text' />`,
    data() {
        return {
           input: '' ,
        }
    },
    methods: {
        monitorEntryKey() {
            //直接调用store在同文件里面可以运行，但是
            //应该使用this.$store, 这是指向在创建Vue对象适合注入的store对象
            //store.dispatch第一个参数是actions的名称
            //第二个参数是payload
            this.$store.dispatch('addNote', this.input)
            this.$store.dispatch('addTimestamp', new Date().toLocaleString());

            this.input = "";
        }
    }
};

const noteCountComponent = {
    template: `
    <div class='note-count'>
        Note count: <strong>{{noteCount}}</strong>
    </div>
    `,
    computed: {
        noteCount() {
            return this.$store.getters.getNoteCount;
        }
    }
}

new Vue({
    el: '#app',
    store,  //注入store
    components: {
        'input-component': inputComponent,
        'note-count-component': noteCountComponent
    },
    computed: {
        notes() {
            return this.$store.getters.getNotes;
        },
        timestamps() {
            return this.$store.getters.getTimestamps;
        }
    }
})